//
//  CZUploadNovelViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/24.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZUploadNovelViewController.h"
#import "CZNovelCell.h"
#import "CZWriteNovelViewController.h"
static NSString *const upload_novel_cell = @"upload_novel_cell";
@interface CZUploadNovelViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *uplodNovelTableView;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (nonatomic, strong) NSMutableArray *novelArray;

@property (nonatomic, strong) LGRefreshView *refreshView;
@property (nonatomic, assign) NSInteger currentPage;
@end

@implementation CZUploadNovelViewController
- (NSMutableArray *__nonnull)novelArray {
    if (!_novelArray) {
        _novelArray = [[NSMutableArray alloc] init];
    }
    return _novelArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上传故事";
    _currentPage = 1;
    _uplodNovelTableView.estimatedRowHeight = 75;
    _uplodNovelTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_uplodNovelTableView registerNib:[UINib nibWithNibName:@"CZNovelCell" bundle:nil] forCellReuseIdentifier:upload_novel_cell];
    self.addBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self postNovelData];
    
    _refreshView = [LGRefreshView refreshViewWithScrollView:self.uplodNovelTableView
                                             refreshHandler:^(LGRefreshView *refreshView){
                                                 [self.uplodNovelTableView.mj_footer setState:(MJRefreshStateIdle)];
                                                 _currentPage = 1;
                                                 [self postNovelData];
                                             }];
    _refreshView.center = CGPointMake(Main_Screen_Width / 2, _refreshView.center.y);
    _refreshView.tintColor = ThemeColor;
    _refreshView.backgroundColor = [UIColor clearColor];
    
    self.uplodNovelTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self postNovelData];
    }];
    self.uplodNovelTableView.mj_footer.hidden = YES;
    

    
    // Do any additional setup after loading the view from its nib.
}
- (void)postNovelData {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/doujin/my-doujins",APP_HOST];
    if (![[NSUserDefaults standardUserDefaults] objectForKey:User_Token]) {
        CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        CZNavigationController *naviVC = rootVC.childViewControllers[0];
        CZMessionCenterViewController *homeVC = (CZMessionCenterViewController *)naviVC.childViewControllers[0];
        CZNavigationController *mineNC = rootVC.childViewControllers[4];
        CZMineViewController *mineVC = mineNC.childViewControllers[0];
        CZUserLoginViewController * loginVC = [[[CZNsjHelper alloc] init] presentLoginViewControllerWithViewCotroller:self];
        @weakify(mineVC);
        loginVC.callBack = ^(){
            [weak_mineVC getUserData];
            [homeVC setUserIconImage];
            weak_mineVC.userIconImageView.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
            [self postNovelData];
        };
        return;
    }
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"page" : @(_currentPage)} success:^(id response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSArray *arr = response[@"result"];
            if (!arr || arr.count < 1) {
                [self.uplodNovelTableView.mj_footer endRefreshingWithNoMoreData];
                [_refreshView endRefreshing];
                return ;
            }
            if (_currentPage == 1) {
                self.novelArray = arr.mutableCopy;
            } else {
                for (NSDictionary *dic in arr) {
                    [self.novelArray addObject:dic];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.uplodNovelTableView reloadData];
                self.uplodNovelTableView.mj_footer.hidden = NO;
            });
            [_refreshView endRefreshing];
            [self.uplodNovelTableView.mj_footer endRefreshing];
        }else if ([response[@"code"] isEqualToString:@"300"]) {
            [_refreshView endRefreshing];
            [self.uplodNovelTableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [_refreshView endRefreshing];
            [self.uplodNovelTableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [_refreshView endRefreshing];
        [self.uplodNovelTableView.mj_footer endRefreshing];
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.novelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZNovelCell *cell = [tableView dequeueReusableCellWithIdentifier:upload_novel_cell];
    cell.timeLabel.hidden = YES;
    cell.statusImageView.hidden = NO;
    cell.statusLabel.hidden = NO;
    NSDictionary *dic = self.novelArray[indexPath.row];
    NSArray *statusImages = @[@"icon_examine", @"icon_adopt", @"icon_refuse"];
    NSArray *titleArr = @[@"审核中", @"已通过", @"未通过"];
    NSString *indexStr = (NSString *)dic[@"verify_status"];
    cell.statusImageView.image = [UIImage imageNamed:statusImages[indexStr.integerValue]];
    cell.statusLabel.text = titleArr[indexStr.integerValue];
    cell.rewardLabel.text = dic[@"reward"];
    cell.authorLabel.text = [NSString stringWithFormat:@"%@ 著", dic[@"author"]];
    cell.novelContentLabel.text = dic[@"doujin_text"];
    cell.novelTitle.text = dic[@"doujin_title"];
    return cell;
}
- (IBAction)addAction:(UIButton *)sender {
    CZWriteNovelViewController *novelVC = [[CZWriteNovelViewController alloc] init];
    novelVC.callBack = ^(BOOL success) {
        if (success) {
            [self postNovelData];
        }
    };
    [self.navigationController pushViewController:novelVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
